package cn.zindesign.utils;

import java.io.*;
import java.util.*;
import java.util.regex.*;

import javax.servlet.http.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;


/**
 * String工具类
 * @author lihui
 * Jan 8, 2012
 */
public class S {

	/** ������־ */
	private static final Log logger = LogFactory.getFactory().getInstance(
			S.class);

	private S() {
	}

	/**
	 * ����ַ�s�Ƿ���a-z����ĸ���
	 * 
	 * @param s
	 * @return boolean
	 */
	public static boolean checkString(String s) {
		boolean tag = false;
		String regex = "\\p{Lower}+?";
		if (s != null && !"".equals(s)) {
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(s);
			tag = m.matches();
		}
		return tag;
	}

	/**
	 * ��������ʽ�ж��ַ��Ƿ���urlencode����
	 * 
	 * @param s
	 *            String
	 * @return boolean
	 */
	public static boolean isUrlEncode(String s) {
		boolean tag = false;
		if (s == null || s.length() < 3) {
			return false;
		}
		if (s.length() > 3) {
			s = s.substring(0, 3);
		}
		String regex = "%[A-Z0-9]{2}";
		if (s != null && !"".equals(s)) {
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(s);
			tag = m.matches();
		}
		return tag;

	}

	/**
	 * ���request.getParameter();
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param name
	 *            String
	 * @param canbenull
	 *            boolean �Ƿ����Ϊ�գ�true ��ʾ����Ϊ�ա�false ��ʾ����Ϊ��
	 * @throws BaseException
	 * @return String
	 */
	public static String getParamValue(HttpServletRequest request, String name) {
		String result = request.getParameter(name);
		if (result == null) {
			result = "";
		}
		if (S.getEncoding(result).equals("ISO-8859-1")) {
			result = S.isoToGb(result);
		}
		return result;
	}

	public static String[] getParamValues(HttpServletRequest request,
			String name) {
		String[] temp = new String[] {};
		String[] result = request.getParameterValues(name);
		if (result == null) {
			result = temp;
		}
		return result;
	}

	/**
	 * �ж������ַ��Ƿ�Ϊgb2312�ı����ʽ
	 * 
	 * @param c
	 *            �����ַ�
	 * @return �����gb2312�����棬���򷵻ؼ�
	 */
	public static boolean isNotGBK(String str) {
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			Character ch = new Character(c);
			String sCh = ch.toString();
			try {
				byte[] bb = sCh.getBytes("GBK");
				if (bb.length > 1) {
					return true;
				}
			} catch (java.io.UnsupportedEncodingException ex) {
				return false;
			}
		}
		return false;
	}

	/**
	 * ���ģʽregex�����ַ�s������ƥ��
	 * 
	 * @param s
	 *            �ַ�
	 * @param regex
	 *            ģʽ
	 * @return boolean true=��ϣ�false=�����
	 */
	public static boolean checkString(String s, String regex) {
		boolean tag = false;
		if (s != null && !"".equals(s)) {
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(s);
			tag = m.matches();
		}
		return tag;
	}

	/**
	 * ���ַ�ת��������
	 * 
	 * @param s
	 *            ��ת�����ַ�
	 * @return int������ַ������֣��򷵻أ�1
	 */
	public static int strToInt(String s) {
		int temp = 0;
		if (hasLength(s)) {
			if (S.isNumeric(s.trim())) {
				temp = Integer.parseInt(s);
			}
		}
		return temp;
	}

	/**
	 * ���ַ�ת����Сд
	 * 
	 * @param s
	 * @return
	 */
	public static String toLowercase(String s) {
		String tag = null;
		if (s != null && !s.equals("")) {
			tag = s.toLowerCase();
		}
		return tag;
	}

	/**
	 * ���ַ�
	 * 
	 * @param s
	 *            �ַ�
	 * @param n
	 *            �ص�λ��
	 * @return
	 */
	public static String getNumString(String s, int n) {
		String tag;
		tag = s;
		if (s != null && !s.equals("")) {
			tag = tag.substring(0, n);
		} else {
			tag = "";
		}
		return tag;
	}
	
	/**
	 * ��λ
	 * @param num
	 * @param length
	 * @return
	 */
	public static String getBuWei(int num,int length){
		int numl = (num+"").length();
		if (numl >= length) {
			return num+"";
		}else{
			String bu = "";
			for (int i = 0; i < length-numl; i++) {
				bu += "0";
			}
			return bu+num;
		}
	}

	/**
	 * �ж��ַ��Ƿ�������
	 * 
	 * @param s
	 * @return �����֣�true;�������֣�false
	 */
	public static boolean isNumeric(String s) {
		boolean flag = true;
		if (hasText(s)) {
			char[] numbers = s.toCharArray();
			for (int i = 0; i < numbers.length; i++) {
				if (!Character.isDigit(numbers[i])) {
					flag = false;
					break;
				}
			}
		} else {
			flag = false;
		}
		return flag;
	}

	public static long strToLong(String s) {
		long temp = -1;
		if (hasLength(s)) {
			if (isNumeric(s)) {
				temp = Long.parseLong(s);
			}
		}
		return temp;
	}

	/**
	 * ��������ʽ4�ж��Ƿ��ǺϷ��ʼ���ַ ���� 2005-07-30
	 * 
	 * @param email
	 *            String
	 * @return boolean
	 */

	public static boolean checkGoodEmail(String email) {
		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(email);
		boolean isMatched = matcher.matches();
		return isMatched;
	}

	/**
	 * ��ʽ�������ı���ʹ�����������һ��
	 * 
	 * @param input
	 *            ����
	 * @return buf
	 */
	public static String formatHTML(String input) {
		if (input == null || input.length() == 0) {
			return input;
		}
		// ��bһ��Stringbuffer 4������������
		StringBuffer buf = new StringBuffer(input.length() + 6);
		char ch = ' ';
		// ����Ƿ��ַ�
		for (int i = 0; i < input.length(); i++) {
			ch = input.charAt(i);
			if (ch == '<') {
				buf.append("&lt;");
			}
			if (ch == '>') {
				buf.append("&gt;");
			}
			if (ch == '\n') {
				buf.append("<br>");
			}
			if (ch == '\r') {
				buf.append("<br>");
			}
			if (ch == '\'') {
				buf.append("&acute");
			}
			if (ch == ' ') {
				buf.append("&nbsp;");
			}
			buf.append(ch);
		}
		return buf.toString();
	}

	public static String formatBr(String input) {
		if (input == null || input.length() == 0) {
			return input;
		}
		// ��bһ��Stringbuffer 4������������
		StringBuffer bf = new StringBuffer("");
		String from = "<>";
		StringTokenizer st = new StringTokenizer(input, from, true);
		while (st.hasMoreTokens()) {
			String tmp = st.nextToken();
			if (tmp != null && tmp.equals("<")) {
				String tmp2 = st.nextToken().toLowerCase();
				if (tmp2.equals("br")) {
					st.nextToken();
					bf = bf.append("");
				}
			} else {
				bf.append(tmp);
			}
		}
		return bf.toString();
	}

	/**
	 * Replace all occurences of a substring within a string with another
	 * string.
	 * 
	 * @param inString
	 *            String to examine
	 * @param oldPattern
	 *            String to replace
	 * @param newPattern
	 *            String to insert
	 * @return a String with the replacements
	 */
	public static String replace(String inString, String oldPattern,
			String newPattern) {
		if (inString == null) {
			return null;
		}
		if (oldPattern == null || newPattern == null) {
			return inString;
		}

		StringBuffer sbuf = new StringBuffer();
		// output StringBuffer we'll build up
		int pos = 0; // our position in the old string
		int index = inString.indexOf(oldPattern);
		// the index of an occurrence we've found, or -1
		int patLen = oldPattern.length();
		while (index >= 0) {
			sbuf.append(inString.substring(pos, index));
			sbuf.append(newPattern);
			pos = index + patLen;
			index = inString.indexOf(oldPattern, pos);
		}
		sbuf.append(inString.substring(pos));

		// remember to append any characters to the right of a match
		return sbuf.toString();
	}

	/**
	 * ��ݿ�ʼstrStart��strEnd��ȡ����source�е�����ַ�
	 * 
	 * @param source
	 *            ԴStringBuffer
	 * @param strStart
	 *            ��ʼ���
	 * @param strEnd
	 *            ������
	 * @return ������ȡ���StringBuffer
	 */

	public static StringBuffer takeString(StringBuffer source, String strStart,
			String strEnd) {
		int start = source.indexOf(strStart) + strStart.length();
		int end = source.indexOf(strEnd);
		if ((end > start) && end != -1 && start != -1) {
			source = new StringBuffer(source.substring(start, end));
			return source;
		}
		return new StringBuffer();
	}

	/*
	 * Function name: split Description: \u5C07�ַ���\u958B��\u6578\u7D44 Input:
	 * \u5C07�ַ�source��\u958B��\u6578\u7D44div(���ӣ�String TTT[] =
	 * my_class.split("aaa:bbb:ccc:ddd",":") ; ) Output: \u6578\u7D44
	 * (����ֵ��TTT[0]="aaa"; TTT[1]="bbb"; TTT[2]="ccc"; TTT[3]="ddd"; )
	 */
	public static String[] split(String toSplit, String delimiter) {
		if (!hasLength(toSplit) || !hasLength(delimiter)) {
			return null;
		}
		int offset = toSplit.indexOf(delimiter);
		if (offset < 0) {
			return null;
		}
		String beforeDelimiter = toSplit.substring(0, offset);
		String afterDelimiter = toSplit.substring(offset + delimiter.length());
		return new String[] { beforeDelimiter, afterDelimiter };
	}

	public static String arrayToDelimitedString(Object[] arr, String delim) {
		if (arr == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			if (i > 0) {
				sb.append(delim);
			}
			sb.append(arr[i]);
		}
		return sb.toString();
	}

	/**
	 * ���ַ���ĳ��char��ʶ��ת��byte[]
	 * 
	 * @param str
	 *            String �ַ����Ϊ����
	 * @param a
	 *            char
	 * @return byte[]
	 */
	public static byte[] strTobytearr(String str, char a) {
		byte[] mykey;
		if (!hasLength(str)) {
			mykey = new byte[0];
		} else {
			String[] arrstr = split(str, a);
			mykey = new byte[arrstr.length];
			for (int k = 0; k < arrstr.length; k++) {
				mykey[k] = Byte.parseByte(arrstr[k]);
			}
		}
		return mykey;
	}

	/**
	 * ��byte[]���鰴�����char a�����һ���ַ�
	 * 
	 * @param mybyte
	 *            byte[]
	 * @param a
	 *            char
	 * @return String
	 */
	public static String bytearrToStr(byte[] mybyte, char a) {
		if (mybyte == null || mybyte.length == 0) {
			return "";
		} else {
			StringBuffer strbuf = new StringBuffer();
			for (int i = 0; i < mybyte.length; i++) {
				strbuf.append(mybyte[i]);
				strbuf.append(a);
			}
			return strbuf.substring(0, strbuf.length() - 1).toString();
		}
	}

	/**
	 * @param name
	 *            ���и���ַ�
	 * @param c
	 *            �и��ַ���ַ�
	 * @return Strin[]
	 */
	public static String[] split(String name, char c) {
		// Figure out the number of parts of the name (this becomes the size
		// of the resulting array).
		if (name == null) {
			return null;
		}
		int size = 1;
		for (int i = 0; i < name.length(); i++) {
			if (name.charAt(i) == c) {
				size++;
			}
		}
		String[] propName = new String[size];
		// Use a StringTokenizer to tokenize the property name.
		StringTokenizer tokenizer = new StringTokenizer(name, String.valueOf(c));
		int i = 0;
		while (tokenizer.hasMoreTokens()) {
			propName[i] = tokenizer.nextToken();
			i++;
		}
		return propName;
	}

	/**
	 * ����ļ������ļ���)չ��
	 * 
	 * @param filename
	 * @return
	 */
	public static String getExt(String filename) {
		if (!S.hasText(filename)) {
			return "";
		}
		if (filename.indexOf(".") < 0) {
			return filename;
		}
		String[] strs = split(filename, '.');
		return strs[strs.length - 1];
	}

	private static final String FOLDER_SEPARATOR = "/"; // folder separator

	private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; // Windows
																	// folder
																	// separator

	private static final String TOP_PATH = ".."; // top folder

	private static final String CURRENT_PATH = "."; // current folder

	/**
	 * Extract the filename from the given path, e.g. "mypath/myfile.txt" ->
	 * "myfile.txt".
	 * 
	 * @param path
	 *            the file path
	 * @return the extracted filename
	 */
	public static String getFilename(String path) {
		int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
		return (separatorIndex != -1 ? path.substring(separatorIndex + 1)
				: path);
	}

	/**
	 * �������·���õ��ļ���·��
	 * 
	 * @param path
	 *            String
	 * @return String
	 */

	public static String getDirPath(String path) {
		int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
		return (separatorIndex != -1 ? path.substring(0, separatorIndex + 1)
				: path);
	}

	/**
	 * �ж��ַ��Ƿ����ַ�����к�д���������滻
	 * 
	 * @param strs
	 *            String[]
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean isInclude(String[] strs, String str) {
		if (strs.length == 0 || str == null || str.length() == 0) {
			return false;
		}
		str = str.toLowerCase();
		for (int i = 0; i < strs.length; i++) {
			if (str.equals(strs[i])) {
				return true;
			}
		}
		return false;
	}



	public static String gbToIso(String str) {
		try {
			if (str != null && !str.equals("")) {
				byte[] byteStr = str.getBytes("gb2312");
				return new String(byteStr, "ISO-8859-1");
			} else {
				return "";
			}
		} catch (Exception e) {
			return str;
		}
	}

	public static String isoToGb(String str) {
		try {
			if (str != null && !str.equals("")) {
				byte[] byteStr = str.getBytes("ISO-8859-1");
				return new String(byteStr, "gb2312");
			} else {
				return "";
			}
		} catch (Exception e) {
			return str;
		}
	}

	/**
	 * Check if a String has length.
	 * <p>
	 * 
	 * <pre>
	 * StringUtils.hasLength(null) = false
	 * StringUtils.hasLength(&quot;&quot;) = false
	 * StringUtils.hasLength(&quot; &quot;) = true
	 * StringUtils.hasLength(&quot;Hello&quot;) = true
	 * </pre>
	 * 
	 * @param str
	 *            the String to check, may be null
	 * @return <code>true</code> if the String is not null and has length
	 */
	public static boolean hasLength(String str) {
		return (str != null && str.length() > 0);
	}

	/**
	 * Check if a String has text. More specifically, returns <code>true</code>
	 * if the string not <code>null<code>, it's <code>length is > 0</code>, and
	 * it has at least one non-whitespace character.
	 * <p><pre>
	 * StringUtils.hasText(null) = false
	 * StringUtils.hasText(&quot;&quot;) = false
	 * StringUtils.hasText(&quot; &quot;) = false
	 * StringUtils.hasText(&quot;null&quot;) = false
	 * StringUtils.hasText(&quot;12345&quot;) = true
	 * StringUtils.hasText(&quot; 12345 &quot;) = true
	 * </pre>
	 * @param str the String to check, may be null
	 * @return <code>true</code> if the String is not null, length > 0,
	 *         and not whitespace only
	 * @see java.lang.Character#isWhitespace
	 */
	public static boolean hasText(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0 || "null".equals(str)) {
			return false;
		}
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * ɾ���ַ����ĳ���ַ�
	 * 
	 * @param pattern
	 *            the pattern to delete all occurrences of
	 */
	public static String delete(String inString, String pattern) {
		return replace(inString, pattern, "");
	}

	/**
	 * Delete any character in a given string.
	 * 
	 * @param charsToDelete
	 *            a set of characters to delete. E.g. "az\n" will delete 'a's,
	 *            'z's and new lines.
	 */
	public static String deleteAny(String inString, String charsToDelete) {
		if (inString == null || charsToDelete == null) {
			return inString;
		}
		StringBuffer out = new StringBuffer();
		for (int i = 0; i < inString.length(); i++) {
			char c = inString.charAt(i);
			if (charsToDelete.indexOf(c) == -1) {
				out.append(c);
			}
		}
		return out.toString();
	}

	/**
	 * �ж�һ���ַ��Ƿ�Ϊ��
	 * 
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean isNull(String str) {
		if (!hasText(str)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * ȥ���ļ����)չ��
	 * 
	 * @param filename
	 * @return
	 */
	public static String delExt(String filename) {
		if (filename.indexOf(".") < 0) {
			return filename;
		}
		String[] strs = split(filename, '.');
		String str = "";
		if (strs.length > 2) {
			for (int i = 0; i < strs.length - 1; i++) {
				str += strs[i];
			}
		} else {
			str = strs[strs.length - 2];
		}
		return str;
	}

	/**
	 * @param source
	 *            ��Ҫ�滻��StringBuffer
	 * @param strS
	 *            ���滻���ַ�
	 * @param strD
	 *            �����滻���ַ�
	 * @return ��strD�ַ��滻source����strS�ַ��� replace(new
	 *         String("kkkk"),"k","e")������"eeee"
	 */
	public static StringBuffer replaceAll(StringBuffer source, String strS,
			String strD) {
		if (strS.equals(strD) || strS.length() == 0) {
			return source;
		}
		int start, offset;
		while (source.indexOf(strS) != -1) {
			start = source.indexOf(strS);
			offset = start + strS.length();
			source.replace(start, offset, strD);
		}
		return source;
	}

	/**
	 * �����ʾ�ַ�
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String getoutPrint(String str) {
		if (str == null || "".equals(str) || "null".equals(str)) {
			return "";
		} else {
			return str;
		}
	}

	/**
	 * �õ�ҳ������в�ѯ���
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return String
	 */
	public static String getQueryString(HttpServletRequest request) {
		String result = "";
		if(request != null) {
			try {
				result = request.getQueryString();
				if (result == null || result.length() < 1) {
					result = "";
					Enumeration qname = request.getParameterNames();
					while (qname.hasMoreElements()) {
						String name = (String) qname.nextElement();
						result += name + "=" + request.getParameter(name) + "&";
					}
					if (result != null && result.length() > 2) {
						result = result.substring(0, result.length() - 1);
					}
				}
			} catch (Exception e) {
			}
		}		
		return result;
	}

	/**
	 * ������Ҫ�ṩ��Pages�ã���4����URL��ַ�е�page �� t �Ĳ�ѯ�����Ҳ���Թ����ظ��Ĳ�ѯ�����
	 * 
	 * @param searchname
	 *            String
	 * @return String
	 */
	public static String getQueryFile(String searchname) {
		Vector v = new Vector();
		try {
			if (searchname != null && searchname.length() > 0) {
				String[] ss = searchname.split("&");
				if (ss != null) {
					searchname = "";
					for (int i = 0; i < ss.length; i++) {
						if (!ss[i].toLowerCase().startsWith("page")
								&& !ss[i].toLowerCase().startsWith("t")
								&& !ss[i].toLowerCase().startsWith("submit")
								&& !ss[i].toLowerCase().startsWith("reset")) {
							for (int j = 0; j < v.size(); j++) {
								int k = ss[i].indexOf("=");
								String temp = "";
								if (k > 0) {
									temp = ss[i].substring(0, k);
								}
								String temp1 = v.get(j).toString();
								if (temp1 != null && temp1.startsWith(temp)) {
									v.removeElementAt(j);
								}
							}
							String[] tt = ss[i].split("=");
							if (tt.length < 2) {
								v.add(tt[0] + "=");
							} else {
								String tt1 = tt[1];
								if (!isUrlEncode(tt1)) {
									tt1 = java.net.URLEncoder.encode(tt1,
											"GB2312");
								}
								v.add(tt[0] + "=" + tt1);
							}
						}
					}
					if (v != null && v.size() > 0) {
						for (int n = 0; n < v.size(); n++) {
							searchname += v.get(n).toString() + "&";
						}
					}
				}
			}
		} catch (Exception e) {
		}
		return searchname;
	}

	/**
	 * �ж��ַ�ı���
	 * 
	 * @param str
	 * @return
	 */
	public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}

	/**
	 * �õ�float��λ���String
	 * 
	 * @param num
	 *            float
	 * @param len
	 *            int
	 * @return String
	 */
	public static String getFloatLen(float num, int len) {
		String numstr = num + "";
		if (numstr.indexOf(".") > 0) {
			String temp = numstr.substring(numstr.indexOf(".") + 1);
			if (temp.length() > len) {
				temp = temp.substring(0, len);
			}
			return numstr.substring(0, numstr.indexOf(".") + 1) + temp;
		}
		return numstr;
	}

	/**
	 * ���ֲ�λ
	 * 
	 * @param num
	 *            int
	 * @param size
	 *            int
	 * @return String
	 */
	public static String fillDigit(int num, int size) {
		String str = String.valueOf(num);
		String temp = "";
		if (str.length() < size) {
			for (int i = 0; i < size - str.length(); i++) {
				temp += "0";
			}
		}
		str = temp + str;
		return str;
	}

	/**
	 * �����滻����ĸ
	 * 
	 * @param num
	 *            int
	 * @return String
	 */
	public static String getLetter(int num) {
		String[] letters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
				"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
				"W", "X", "Y", "Z" };
		if (num < 0) {
			return "Z";
		}
		if (num > 25) {
			return "Z";
		}
		return letters[num];
	}

	/**
	 * ������ת�����ַ�
	 * 
	 * @param array
	 *            String[] ����
	 * @param sign
	 *            String �ָ���
	 * @return String
	 */
	public static String convertArraytoString(String[] array, String sign) {
		String result = "";
		if (array == null) {
			return "";
		}
		for (int i = array.length; i > 0; i--) {
			result += array[i - 1];
			if (i > 1) {
				result += sign;
			}
		}
		return result;
	}

	/**
	 * �ṩ��ȷ��С��λ�������봦�?
	 * 
	 * @param v
	 *            ��Ҫ�������������
	 * @param scale
	 *            С������λ
	 * @return ���������Ľ��
	 */
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * �ṩ����ԣ���ȷ�ĳ����㡣�����������ʱ����scale����ָ �����ȣ��Ժ�������������롣
	 * 
	 * @param v1
	 *            ������
	 * @param v2
	 *            ����
	 * @param scale
	 *            ��ʾ��ʾ��Ҫ��ȷ��С����Ժ�λ��
	 * @return }��������
	 */
	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static String getPercent(double v1, double v2) {
		double v = div(v1, v2, 2);
		String s = Double.toString(v);
		String[] as = split(s, '.');
		int i = Integer.parseInt(as[0]);
		String p = "0";
		if (i == 0) {
			p = getExt(s);
		} else {
			p = as[0] + as[1];
		}
		return p + "%";
	}

	/**
	 * ��ȡһ�����ֶ�
	 * 
	 * @param tablename
	 *            String
	 * @param sqlprotasis
	 *            String
	 * @param columnname
	 *            String[]
	 * @return String
	 */
	public static String getSubString(int size, String str) {
		String Str = "";
		if (str == null) {
			return "";
		}
		int size1 = size * 2;
		if (str.length() > size) {
			for (int i = 0; i < size1; i++) {
				int x = 1;
				int j = str.charAt(i);
				if (j > 200) {
					size1 = size1 - 1;
				}
				if (i >= str.length() - 1) {
					break;
				}
				Str += str.charAt(i);
			}
			Str = Str + "";
		} else {
			Str = str;
		}
		return Str;
	}
	
	public static int getEnSize(String str){
		String Str = "";
		if (str == null) {
			return 0;
		}
		int size1 = 0;
		for (int i = 0; i < str.length(); i++) {
			int j = str.charAt(i);
			if (j <= 200) {
				size1 ++;
			}
		}
		return size1;
	}
	
	public static int getStrSizeInCludeEnStr(String str){
		String Str = "";
		if (str == null) {
			return 0;
		}
		int size1 = 0;
		for (int i = 0; i < str.length(); i++) {
			int j = str.charAt(i);
			if (j > 200) {
				size1 = size1+2;
			}else{
				size1 = size1+1;
			}
		}
		return size1;
	}

	/**
	 * ��������ʽ�滻���е�html���
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String delHtmlTag(String str) {
		if (str == null) {
			return "";
		}
		String regex = "<(.[^>]*)>";
		str = str.replaceAll(regex, " ");
		return str;
	}

	/**
	 * ��������ʽ�滻���е�html���
	 * 
	 * @param resouce
	 *            String
	 * @param resouce
	 *            str
	 * @return String
	 */
	public static String replaceHtmlTag(String resouce, String str) {
		if (resouce == null) {
			return "";
		}
		String regex = "<(.[^>]*)>";
		str = resouce.replaceAll(regex, str);
		return str;
	}

	/**
	 * �����Դ��)չ����ж���Դ������
	 * 
	 * @param x
	 *            String
	 * @return String
	 */
	public static String getImgFromExt(String x) {
		x = S.toLowercase(x);
		String s = "";
		if (x.equals("txt") || x.equals("ini") || x.equals("rtf")
				|| x.equals("bat")) {
			s = "txt.gif"; // �ı�����Դ
		} else if (x.equals("chm")) {
			s = "hlp.gif";
		} else if (x.equals("htm") || x.equals("html")) {
			s = "htm.gif";
		} else if (x.equals("xml")) {
			s = "xml.gif";
		} else if (x.equals("gif") || x.equals("jpeg") || x.equals("jpg")
				|| x.equals("tiff") || x.equals("png") || x.equals("pad")
				|| x.equals("tif") || x.equals("bmp")) {
			s = "pic.gif"; // ͼ��ͼ������Դ
		} else if (x.equals("wmf") || x.equals("gsp") || x.equals("gss")
				|| x.equals("mov") || x.equals("mno") || x.equals("mmc")
				|| x.equals("avi") || x.equals("au") || x.equals("atx")
				|| x.equals("ram") || x.equals("aif") || x.equals("asf")
				|| x.equals("mpeg") || x.equals("mpg") || x.equals("peg")) {
			s = "mp.gif"; // ��Ƶ����Դ
		} else if (x.equals("rm") || x.equals("wav") || x.equals("mp3")
				|| x.equals("mid") || x.equals("mpv")) {
			s = "rm.gif"; // ��Ƶ����Դ
		} else if (x.equals("swf") || x.equals("fla")) {
			s = "swf.gif"; // ��������Դ
		} else if (x.equals("exe") || x.equals("msi") || x.equals("com")) {
			s = "exe.gif"; // ��ѧ���ߺ�ģ��
		} else if (x.equals("zip") || x.equals("rar")) {
			s = "zip.gif";
		} else if (x.equals("mdb")) {
			s = "mdb.gif";
		} else if (x.equals("pps") || x.equals("ppt") || x.equals("prj")
				|| x.equals("mathematica") || x.equals("���λ���")
				|| x.equals("msw")) {
			s = "ppt.gif"; // ��ѧ����
		} else if (x.equals("pdf")) {
			s = "pdf.gif"; // ������
		} else if (x.equals("doc")) {
			s = "doc.gif"; // �̰�������
		} else if (x.equals("xl") || x.equals("xls")) {
			s = "xls.gif";
		} else {
			s = "unknow.gif";
		}
		return s;
	}

	/**
	 * �ַ�ȥ��β�Ŀո�
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String getStrValue(String str) {
		String name = str;
		if ((name != null) && (name.length() > 0)) {
			name = name.trim();
		}
		return name;
	}

	/**
	 * �ж��ַ��Ƿ�Ϊ�ն���,�����ÿմ�,���򷵻�ԭֵ
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String isString(String str) {
		if (str == null) {
			str = "";
		}
		return str;
	}

	/**
	 * �ж�����������Ƿ�Ϊ��,������ϵͳ��ǰʱ��,���򷵻�ԭֵ
	 * 
	 * @param date
	 *            Date
	 * @return Date
	 */
	public static Date isDate(Date date) {
		if (date == null) {
			date = new Date();
		}
		return date;
	}

	/**
	 * �ж�Float����Ƿ�Ϊ��,������0.00,���򷵻�ԭֵ
	 * 
	 * @param floatValue
	 *            Float
	 * @return Date
	 */
	public static Float isFloat(Float floatValue) {
		if (floatValue == null) {
			floatValue = new Float("0");
		}
		return floatValue;
	}

	/**
	 * �ж���������Ƿ�Ϊ��,������0,���򷵻�ԭֵ
	 * 
	 * @param intValue
	 *            Integer
	 * @return Integer
	 */
	public static Integer isInt(Integer intValue) {
		if (intValue == null) {
			intValue = 0;
		}
		return intValue;
	}

	// ��־����
	public static final Log myLog(String classname) {
		Log log = LogFactory.getFactory().getInstance(classname);
		if (log == null) {
			log = LogFactory.getFactory().getInstance("log is null");
		}
		return log;
	}

	// ������ʽ�滻
	public static String replaceStr(String oldString, String newString,
			String regex) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(oldString);
		String str = "";
		if (m.find()) {
			str = m.replaceAll(newString);
		} else {
			if (oldString != null && !oldString.equals("")) {
				str = oldString;
			} else {
				str = "";
			}
		}
		return str;
	}

	// ///////////////add by gamebus
	/**
	 * encodeת��
	 * 
	 * @param str
	 * @return �ǿշ���str��Ϊ�շ���""
	 */
	public static String encode(String str) {
		try {
			if (str != null) {
				return (new String(str.getBytes("iso-8859-1"), "gb2312"));
			} else {
				return "";
			}
		} catch (Exception e) {
			return e.toString();
		}
	}

	public static String toTrim(String s) {
		if (hasText(s)) {
			return s.trim();
		}
		return "";
	}

	public static String formatFromHtml(String input) {
		if (input == null || input.length() == 0) {
			return "";
		}
		input = input.replaceAll("<br>", "\n").replaceAll("&lt;", "<")
				.replaceAll("&gt;", ">").replaceAll("&acute", "\'").replaceAll(
						"&nbsp;", " ");
		return input;

	}

	/**
	 * �ж��ַ����Ƿ���������
	 * 
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean includeChinese(String str) {
		if (str == null) {
			return false;
		}
		for (int i = 0; i < str.length(); i++) {
			int j = str.charAt(i);
			if (j > 200) {
				return true;
			}
		}
		return false;
	}

	// ��ɵ����ֶ����
	public static String single1SearchContent(String searchname,
			String searchtype, String column) {
		if (searchname != null && !"".equals(searchname)) {
			if ("1".equals(searchtype)) {
				return " and " + column + " = '" + searchname + "'";
			} else {
				return " and " + column + " like '%" + searchname + "%'";
			}
		}
		return "";
	}

	public static String singleParameter(String name, String value) {
		if (name != null && !"".equals(name)) {
			return "&" + name + "=" + value;
		}
		return "";
	}

	public static String rootpath = "";

	/**
	 * ɾ��ĳĿ¼�µ�ָ���ļ�
	 * 
	 * @param filecatalog
	 *            Ŀ¼�б�
	 * @param filename
	 *            �ļ��� String[]
	 */
	public static void delFile(String filecatalog, String[] filename) {
		File delfile;
		String fname = "", name = "";
		try {
			for (int i = 0; i < filename.length; i++) {
				name = filename[i];
				if (name != null && !name.equals("")) {
					fname = rootpath + filecatalog + name;
					delfile = new File(fname);
					if (delfile.exists()) { // �ж��ļ��Ƿ����
						delfile.delete();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ���ָ���ָ�����ָ���ַ�
	public static List split(List list, String inputString, String separator) {
		int offset = inputString.indexOf(separator);
		if (offset >= 0) {
			list.add(inputString.substring(0, offset));
			split(list, inputString.substring(offset + separator.length()),
					separator);
		} else {
			list.add(inputString);
		}
		return list;
	}

	public static StringBuffer replace(StringBuffer source, String regex,
			String newString) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(source);
		String str = "";
		if (m.find()) {
			str = m.replaceAll(newString);
			source.replace(0, source.length(), str);
		}
		return source;
	}
	
	public static String getString4Analusis(String content){
		content=S.delHtmlTag(content);
        content = S.replaceStr(content,"","\\s");
        content = S.replaceStr(content,"\"","&ldquo;");
        content = S.replaceStr(content,"\"","&rdquo;");
        content = S.replaceStr(content,"\"","&quot;");
        content = S.replaceStr(content,"","&nbsp;");
        return content;
	}
	
	public static String subStringHTML(String param,int length,String end) {
	     StringBuffer result = new StringBuffer();
	     int n = 0;
	     char temp;
	     boolean isCode = false; //�ǲ���HTML����
	     boolean isHTML = false; //�ǲ���HTML�����ַ�,��&nbsp;
	     for (int i = 0; i < param.length(); i++) {
	       temp = param.charAt(i);
	       if (temp == '<') {
	         isCode = true;
	       }
	       else if (temp == '&') {
	         isHTML = true;
	       }
	       else if (temp == '>' && isCode) {
	         n = n - 1;
	         isCode = false;
	       }
	       else if (temp == ';' && isHTML) {
	         isHTML = false;
	       }

	       if (!isCode && !isHTML) {
	         n = n + 1;
	         //UNICODE���ַ�ռ}���ֽ�
	         if ( (temp + "").getBytes().length > 1) {
	           n = n + 1;
	         }
	       }

	       result.append(temp);
	       if (n >= length) {
	         break;
	       }
	     }
	     result.append(end);
	     //ȡ���ȡ�ַ��е�HTML���
	     String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
	     //ȥ����Ҫ���ر�ǵ�HTML���
	     temp_result = temp_result.replaceAll("</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
	                                          "");
	     //ȥ��ɶԵ�HTML���
	     temp_result=temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>","$2");
	     //��������ʽȡ����
	     Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
	     Matcher m = p.matcher(temp_result);

	     List endHTML = new ArrayList();

	     while (m.find()) {
	       endHTML.add(m.group(1));
	     }
	     //��ȫ���ɶԵ�HTML���
	     for (int i = endHTML.size() - 1; i >= 0; i--) {
	       result.append("</");
	       result.append(endHTML.get(i));
	       result.append(">");
	     }

	     return result.toString();
	   }
	
	public static String delLastTag(String str,String tag){
		if (isNull(str)) {
			return "";
		}
		if (isNull(tag)) {
			return str;
		}
		if (str.length() <= tag.length()) {
			return str;
		}
		return str.substring(0,str.length()-tag.length());
	}
	
	/**
	 * add by lihui 2009.9.14
	 * ��ʽ����ǩ����FCK�����Ÿ�ʽ�����ƽ̨��ǩ���,������heip4ϵͳ����ǩStyleInfoIterate
	 * 
	 * @param input
	 *            ����
	 * @return buf
	 */
	public static String formatFCK2HTML(String input) {
		if (input == null || input.length() == 0) {
			return "";
		}
		input = input.replaceAll("&quot;", "\"").replaceAll("&lt;FCK:", "<")
				.replaceAll("&gt;", ">").replaceAll("&acute", "\'").replaceAll(
						"&lt;/FCK:", "</");
		return input;
	}
	
	/**
	 * 将null转成“”，其他不变
	 * by lihui in Jan 8, 2012 5:00:01 PM
	 * @param str
	 * @return
	 */
	public static String stringNoNull(String str){
		if(str==null){
			return "";
		}else{
			return str;
		}
	}
	
	/**
	 * 非空判断
	 * by lihui in Jan 8, 2012 9:48:31 PM
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str){
		if(str!=null&&!str.equals("")){
			return true;
		}else{
			return false;
		}
		
	}
	
	

}
